package servlet;

import dao.MyDb;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * Created by lenovo on 2018/9/26.
 */

public class LoginServlet extends HttpServlet{
  MyDb myDb = new MyDb();
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        String op = request.getParameter("op");
        PrintWriter out = response.getWriter();
        if(op == null){
            op = "";
        }
        System.out.println(op);
        switch (op){
            case "register":
                register(request,response);
                break;

            case "login":
                login(request,response);
                break;

        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        User user = new User();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        user.setPassword(password);
        user.setName(name);
        if(myDb.isExist("select *from user where name=? and pasword=?",new String[]{String.valueOf(user.getName()),user.getPassword()})){
            request.getSession().setAttribute("islogin","yes");
            response.sendRedirect("success.jsp");
            return ;
        }else{
            request.getSession().setAttribute("error","无效的用户和密码");
            request.getSession().setAttribute("islogin",null);
            response.sendRedirect("login.jsp");
        }
    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        User user = new User();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        user.setPassword(password);
        user.setName(name);
        if(myDb.isExist("select *from user where name=? and pasword=?",new String[]{String.valueOf(user.getName()),user.getPassword()})){
            request.getSession().setAttribute("wzc","exist");
            response.sendRedirect("register.jsp");
            return ;
        }
        String sql="insert into user values('"+user.getName()+"','"+user.getPassword()+"')";
        myDb.executeUpdate(sql);
        response.sendRedirect("login.jsp");
    }



}
